'''
Created on 2014-2-24

@author: apple
'''
def send_email(subject, to, content, content_subtype):
    from django.core import mail
    from com.ad.sword.dao.models import SystemConfig

    from_email = None
    smtp_config = {}
    config = SystemConfig.objects(name__startswith="smtp_")
    for c in config:
        name = unicode(c.name)[5:]
        value = unicode(c.value)
        if name == "use_tls":
            if value.lower() == "yes" or value.lower() == "true" or value == "1":
                smtp_config[name] = True
            else:
                smtp_config[name] = False
        elif name == "from_email":
            from_email = value
        elif name == "port":
            smtp_config[name] = int(value)
        else:
            smtp_config[name] = value

    connection = mail.get_connection(fail_silently=False, **smtp_config)
    connection.open()
    try:
        if isinstance(to, list):
            msg = mail.EmailMessage(subject, content, from_email = from_email, to = to, connection = connection)
        else:
            msg = mail.EmailMessage(subject, content, from_email = from_email, to = to.split(","), connection = connection)

        msg.content_subtype = content_subtype
        msg.send()
    finally:
        connection.close()

def send_text_email(subject, to, content):
    return send_email(subject, to, content, "text")


def send_html_email(subject, to, content):
    return send_email(subject, to, content, "html")